package com.uduemc.biso.node.web.api.design.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.uduemc.biso.node.web.api.exception.NotFoundException;

import lombok.extern.slf4j.Slf4j;

@Controller
@RequestMapping("/api/design")
@Slf4j
public class DHtmlController {

	@GetMapping(value = { "/*/*/html/baidumap.html" })
	public ModelAndView baidumap(ModelAndView modelAndValue) throws NotFoundException {
		modelAndValue.setViewName("design/html/baidumap");
		return modelAndValue;
	}

	@GetMapping(value = { "/*/*/html/googlemap.html" })
	public ModelAndView googlemap(ModelAndView modelAndValue) throws NotFoundException {
		modelAndValue.setViewName("design/html/googlemap");
		return modelAndValue;
	}

	@GetMapping(value = { "/*/*/html/qrcode.html" })
	@ResponseBody
	public ResponseEntity<byte[]> qrcode(@RequestParam("qr") String qr,
			@RequestParam(name = "w", required = false, defaultValue = "300") int w,
			@RequestParam(name = "h", required = false, defaultValue = "300") int h) throws NotFoundException {
		// 二维码内的信息
		String info = qr;
		byte[] qrcode = null;
		try {
			qrcode = getQRCodeImage(info, w, h);
		} catch (WriterException e) {
			log.debug("Could not generate QR Code, WriterException :: " + e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			log.debug("Could not generate QR Code, IOException :: " + e.getMessage());
		}
		// Set headers
		final HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.IMAGE_PNG);
		return new ResponseEntity<byte[]>(qrcode, headers, HttpStatus.CREATED);
	}

	public static byte[] getQRCodeImage(String text, int width, int height) throws WriterException, IOException {
		QRCodeWriter qrCodeWriter = new QRCodeWriter();
		BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
		ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
		MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOutputStream);
		byte[] pngData = pngOutputStream.toByteArray();
		return pngData;
	}
}
